// 家人页面脚本
let mediaRecorder = null;
let audioChunks = [];
let audioBlob = null;
let selectedPhoto = null;

// 获取URL参数
function getUrlParams() {
    const path = window.location.pathname;
    const parts = path.split('/');
    return {
        employeeId: parts[2],
        messageId: parts[3]
    };
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    document.getElementById('startRecording').addEventListener('click', startRecording);
    document.getElementById('stopRecording').addEventListener('click', stopRecording);
    document.getElementById('photoInput').addEventListener('change', handlePhotoSelect);
    document.getElementById('submitBtn').addEventListener('click', submitMessage);
}

// 开始录音
async function startRecording() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        
        mediaRecorder = new MediaRecorder(stream);
        audioChunks = [];
        
        mediaRecorder.ondataavailable = function(event) {
            audioChunks.push(event.data);
        };
        
        mediaRecorder.onstop = function() {
            audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            showPreview();
        };
        
        mediaRecorder.start();
        
        document.getElementById('startRecording').classList.add('hidden');
        document.getElementById('stopRecording').classList.remove('hidden');
        document.getElementById('recordingStatus').textContent = '正在录音...';
        document.getElementById('recordingStatus').classList.add('text-red-600');
        
        // 30秒后自动停止
        setTimeout(() => {
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                stopRecording();
            }
        }, 30000);
        
    } catch (error) {
        alert('无法访问麦克风，请检查权限设置');
    }
}

// 停止录音
function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
        mediaRecorder.stream.getTracks().forEach(track => track.stop());
        
        document.getElementById('startRecording').classList.remove('hidden');
        document.getElementById('stopRecording').classList.add('hidden');
        document.getElementById('recordingStatus').textContent = '录音完成';
        document.getElementById('recordingStatus').classList.remove('text-red-600');
    }
}

// 处理照片选择
function handlePhotoSelect(event) {
    const file = event.target.files[0];
    if (file) {
        selectedPhoto = file;
        
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('previewImage').src = e.target.result;
            document.getElementById('photoPreview').classList.remove('hidden');
            document.getElementById('previewArea').classList.remove('hidden');
            document.getElementById('submitBtn').classList.remove('hidden');
        };
        reader.readAsDataURL(file);
    }
}

// 显示预览
function showPreview() {
    if (audioBlob) {
        const audioUrl = URL.createObjectURL(audioBlob);
        document.getElementById('audioSource').src = audioUrl;
        document.getElementById('audioPreview').classList.remove('hidden');
        document.getElementById('previewArea').classList.remove('hidden');
        document.getElementById('submitBtn').classList.remove('hidden');
    }
}

// 提交消息
async function submitMessage() {
    if (!audioBlob && !selectedPhoto) {
        alert('请至少录制语音或上传照片');
        return;
    }
    
    const { employeeId } = getUrlParams();
    
    const formData = new FormData();
    
    if (audioBlob) {
        formData.append('voice', audioBlob, 'family-message.wav');
    }
    
    if (selectedPhoto) {
        formData.append('photo', selectedPhoto);
    }
    
    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>生成中...';
    document.getElementById('submitBtn').disabled = true;
    
    try {
        const response = await fetch(`/api/upload-family-message/${employeeId}`, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('qrCode').src = `/${data.qrCode}`;
            document.getElementById('qrDisplayArea').classList.remove('hidden');
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-check mr-2"></i>生成成功';
            
            // 滚动到二维码区域
            document.getElementById('qrDisplayArea').scrollIntoView({ behavior: 'smooth' });
        } else {
            alert('生成失败，请重试');
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-paper-plane mr-2"></i>重新生成';
            document.getElementById('submitBtn').disabled = false;
        }
    } catch (error) {
        alert('网络错误，请重试');
        document.getElementById('submitBtn').innerHTML = '<i class="fas fa-paper-plane mr-2"></i>重新生成';
        document.getElementById('submitBtn').disabled = false;
    }
}
